package com.migu.contacts.main.create;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.migu.contacts.net.Service.API;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.frank.libandroid.BaseActivity;
import com.frank.libandroid.BaseAdapter;
import com.frank.libandroid.BottomPopup;
import com.frank.libandroid.DataStore;
import com.frank.libandroid.GsonUtil;
import com.frank.libandroid.HttpCallback;
import com.frank.libandroid.butterknife.BindAdapter;
import com.frank.libandroid.butterknife.OnClick;
import com.frank.libandroid.util.ConstellationUtil;
import com.frank.libandroid.util.ImageUtil;
import com.frank.libandroid.util.RadioGroupUtil;
import com.github.gzuliyujiang.wheelpicker.contract.LinkageProvider;
import com.github.gzuliyujiang.wheelview.contract.WheelFormatter;
import com.google.gson.reflect.TypeToken;
import com.haibin.calendarview.LunarUtil;
import com.lxj.xpopup.XPopup;
import com.migu.contacts.BuildConfig;
import com.migu.contacts.R;
import com.migu.contacts.bean.AddressBean;
import com.migu.contacts.bean.BirthdayTip;
import com.migu.contacts.bean.ContactBean;
import com.migu.contacts.bean.FestivalTip;
import com.migu.contacts.bean.GiftTip;
import com.migu.contacts.bean.GroupBean;
import com.migu.contacts.bean.IndustryBean;
import com.migu.contacts.bean.LabelBean;
import com.migu.contacts.bean.PositionBean;
import com.migu.contacts.databinding.ActivityContactCreateBinding;
import com.migu.contacts.databinding.CommonLabel3Binding;
import com.migu.contacts.databinding.ContactEditAddressBinding;
import com.migu.contacts.databinding.ContactEditIndustryBinding;
import com.migu.contacts.databinding.ContactEditMarryBinding;
import com.migu.contacts.databinding.ContactEditPositionBinding;
import com.migu.contacts.databinding.ContactEditSexPopBinding;
import com.migu.contacts.databinding.ContactEditXueliBinding;
import com.migu.contacts.databinding.ItemContactEditContactBinding;
import com.migu.contacts.databinding.ItemDetailMidBinding;
import com.migu.contacts.databinding.ItemDetailTopBinding;
import com.migu.contacts.databinding.ItemEditCommonBinding;
import com.migu.contacts.databinding.ItemEditGroupBinding;
import com.migu.contacts.databinding.ItemEditLabelBinding;
import com.migu.contacts.databinding.ItemSelectGroupDetailBinding;
import com.migu.contacts.databinding.PopContactEditCommonBinding;
import com.migu.contacts.main.BirthdayActivity;
import com.migu.contacts.main.ContactEditActivity;
import com.migu.contacts.main.ContactSelectActivity;
import com.migu.contacts.main.CycleActivity;
import com.migu.contacts.main.FestivalActivity;
import com.migu.contacts.main.GiftActivity;
import com.migu.contacts.main.GroupActivity;
import com.migu.contacts.main.LabelActivity;
import com.migu.contacts.util.AddressUtil;
import com.migu.contacts.util.AvatarUtil;
import com.migu.contacts.util.DateUtil;
import com.migu.contacts.util.EduUtil;
import com.migu.contacts.util.GroupUtil;
import com.migu.contacts.util.LabelUtil;
import com.migu.contacts.util.MarryUtil;
import com.migu.contacts.util.PictureUtil;
import com.migu.contacts.util.PopUtil;
import com.migu.contacts.util.SexUtil;
import com.migu.contacts.util.StringUtil;
import com.migu.contacts.widget.Callback;
import com.migu.contacts.widget.Label;
import com.migu.contacts.widget.Label3;

import org.greenrobot.eventbus.EventBus;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class ContactCreateActivity extends BaseActivity<ActivityContactCreateBinding> {

    @BindAdapter(R.id.recyclerView)
    BaseAdapter<ItemDetailTopBinding, Label.LabelBean> topAdapter = new BaseAdapter<ItemDetailTopBinding, Label.LabelBean>() {
        @OnClick(R.id.iv_arrow)
        public void clickRight(int position, Label.LabelBean bean) {
            Log.d(TAG, "clickRight() called with: position = [" + position + "], bean = [" + bean + "]");
            if (position == 0) {
                BottomPopup bottomPopup = new BottomPopup<ContactEditSexPopBinding>(mActivity) {
                    @OnClick(R.id.close)
                    public void quit() {
                        dismiss();
                    }

                    List<String> list = Arrays.asList("男",
                            "女");

                    @Override
                    protected void initView() {
                        super.initView();
                        mBinding.edu.setData(list);
                    }

                    @OnClick(R.id.confirm)
                    public void confirm() {
                        int currentPosition = mBinding.edu.getCurrentPosition();
                        bean.right = list.get(currentPosition);
                        contactBean.gender = currentPosition + 1;
                        topAdapter.notifyDataSetChanged();
                        if (TextUtils.isEmpty(contactBean.avatar)) {
                            if (currentPosition == 0) {
                                ContactCreateActivity.this.mBinding.avatar.setImageResource(R.drawable.avatar_male);
                            } else {
                                ContactCreateActivity.this.mBinding.avatar.setImageResource(R.drawable.avatar_female);
                            }
                        }
                        dismiss();
                    }

                };
                new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
            } else if (position == 2) {
                PopUtil.showDatePicker(mActivity, contactBean.lunarBirthday, new Callback<String>() {
                    @Override
                    public void onComplete(String string) {
                        LocalDate date = LocalDate.parse(string);
                        contactBean.lunarBirthday = string;
                        bean.right = string;

                        LocalDate solarDate = DateUtil.lunar2Solar(date);
                        contactBean.birthday = solarDate.toString();
                        topAdapter.getData().get(3).right = solarDate.toString();
                        LocalDate now = LocalDate.now();
                        long days = ChronoUnit.DAYS.between(solarDate, now);
                        int age = (int) (days / 365);
                        if (days % 365 != 0) {
                            age++;
                        }
                        contactBean.age = age;
                        contactBean.constellation = ConstellationUtil.getConstellation(solarDate);
                        topAdapter.getData().get(4).right = age + "";
                        Log.d(TAG, "confirm() called" + string);
                        topAdapter.getData().get(5).right = contactBean.constellation;
                        topAdapter.notifyDataSetChanged();
                    }
                });
            } else if (position == 3) {
                PopUtil.showDatePicker(mActivity, contactBean.birthday, new Callback<String>() {
                    @Override
                    public void onComplete(String string) {
                        LocalDate localDate = LocalDate.parse(string);
                        contactBean.birthday = string;
                        bean.right = string;
                        int[] ints = LunarUtil.solarToLunar(localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth());
                        LocalDate lunarDate = LocalDate.of(ints[0], ints[1], ints[2]);
                        String lunarString = lunarDate.toString();
                        contactBean.lunarBirthday = lunarString;
                        topAdapter.getData().get(2).right = lunarString;

                        LocalDate now = LocalDate.now();
                        long days = ChronoUnit.DAYS.between(localDate, now);
                        int age = (int) (days / 365);
                        if (days % 365 != 0) {
                            age++;
                        }
                        contactBean.age = age;
                        contactBean.constellation = ConstellationUtil.getConstellation(localDate);
                        topAdapter.getData().get(4).right = age + "";
                        Log.d(TAG, "confirm() called" + string);
                        topAdapter.getData().get(5).right = contactBean.constellation;
                        topAdapter.notifyDataSetChanged();
                    }
                });
            } else if (position == 8) {
                BottomPopup bottomPopup = new BottomPopup<ContactEditAddressBinding>(mActivity) {
                    @OnClick(R.id.close)
                    public void quit() {
                        dismiss();
                    }

                    @OnClick(R.id.confirm)
                    public void confirm() {
                        AddressBean first = mBinding.address.getFirstWheelView().getCurrentItem();
                        AddressBean second = mBinding.address.getSecondWheelView().getCurrentItem();
                        AddressBean third = mBinding.address.getThirdWheelView().getCurrentItem();
                        bean.right = first.name + second.name + third.name;
                        topAdapter.notifyDataSetChanged();
                        if (contactBean.currentAddress == null) {
                            contactBean.currentAddress = new ContactBean.Address();
                        }
                        contactBean.currentAddress.provinceCode = first.code;
                        contactBean.currentAddress.cityCode = second.code;
                        contactBean.currentAddress.countyCode = third.code;
                        dismiss();
                    }


                    @Override
                    protected void initView() {
                        super.initView();
                        WheelFormatter first = new WheelFormatter() {
                            @Override
                            public String formatItem(@NonNull Object item) {
                                return ((AddressBean) item).name;
                            }
                        };
                        mBinding.address.setFormatter(first, first, first);
                        mBinding.address.setDefaultValue(addressLevel1.get(0), null, null);
                        mBinding.address.setData(new LinkageProvider() {
                            @Override
                            public boolean firstLevelVisible() {
                                return true;
                            }

                            @Override
                            public boolean thirdLevelVisible() {
                                return true;
                            }

                            @NonNull
                            @Override
                            public List<?> provideFirstData() {
                                Log.d(TAG, "provideFirstData() called");
                                return addressLevel1;
                            }

                            @NonNull
                            @Override
                            public List<?> linkageSecondData(int firstIndex) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                return addressMap.get(addressBean.code);
                            }

                            @NonNull
                            @Override
                            public List<?> linkageThirdData(int firstIndex, int secondIndex) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                AddressBean bean1 = addressMap.get(addressBean.code).get(secondIndex);
                                return addressMap.get(bean1.code);
                            }

                            @Override
                            public int findFirstIndex(Object firstValue) {
                                return addressLevel1.indexOf(firstValue);
                            }

                            @Override
                            public int findSecondIndex(int firstIndex, Object secondValue) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                List<AddressBean> list = addressMap.get(addressBean.code);
                                return list.indexOf(secondValue);
                            }

                            @Override
                            public int findThirdIndex(int firstIndex, int secondIndex, Object thirdValue) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                List<AddressBean> list = addressMap.get(addressBean.code);
                                AddressBean bean1 = list.get(secondIndex);
                                List<AddressBean> list1 = addressMap.get(bean1.code);
                                return list1.indexOf(thirdValue);
                            }
                        });
                    }
                };
                new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
            } else if (position == 9) {
                BottomPopup bottomPopup = new BottomPopup<ContactEditAddressBinding>(mActivity) {
                    @OnClick(R.id.close)
                    public void quit() {
                        dismiss();
                    }

                    @OnClick(R.id.confirm)
                    public void confirm() {
                        AddressBean first = mBinding.address.getFirstWheelView().getCurrentItem();
                        AddressBean second = mBinding.address.getSecondWheelView().getCurrentItem();
                        AddressBean third = mBinding.address.getThirdWheelView().getCurrentItem();
                        bean.right = first.name + second.name + third.name;
                        topAdapter.notifyDataSetChanged();
                        if (contactBean.homeAddress == null) {
                            contactBean.homeAddress = new ContactBean.Address();
                        }
                        contactBean.homeAddress.provinceCode = first.code;
                        contactBean.homeAddress.cityCode = second.code;
                        contactBean.homeAddress.countyCode = third.code;
                        dismiss();
                    }


                    @Override
                    protected void initView() {
                        super.initView();
                        WheelFormatter first = new WheelFormatter() {
                            @Override
                            public String formatItem(@NonNull Object item) {
                                return ((AddressBean) item).name;
                            }
                        };
                        mBinding.address.setFormatter(first, first, first);
                        mBinding.address.setData(new LinkageProvider() {
                            @Override
                            public boolean firstLevelVisible() {
                                return true;
                            }

                            @Override
                            public boolean thirdLevelVisible() {
                                return true;
                            }

                            @NonNull
                            @Override
                            public List<?> provideFirstData() {
                                Log.d(TAG, "provideFirstData() called");
                                return addressLevel1;
                            }

                            @NonNull
                            @Override
                            public List<?> linkageSecondData(int firstIndex) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                return addressMap.get(addressBean.code);
                            }

                            @NonNull
                            @Override
                            public List<?> linkageThirdData(int firstIndex, int secondIndex) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                AddressBean bean1 = addressMap.get(addressBean.code).get(secondIndex);
                                return addressMap.get(bean1.code);
                            }

                            @Override
                            public int findFirstIndex(Object firstValue) {
                                return addressLevel1.indexOf(firstValue);
                            }

                            @Override
                            public int findSecondIndex(int firstIndex, Object secondValue) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                List<AddressBean> list = addressMap.get(addressBean.code);
                                return list.indexOf(secondValue);
                            }

                            @Override
                            public int findThirdIndex(int firstIndex, int secondIndex, Object thirdValue) {
                                AddressBean addressBean = addressLevel1.get(firstIndex);
                                List<AddressBean> list = addressMap.get(addressBean.code);
                                AddressBean bean1 = list.get(secondIndex);
                                List<AddressBean> list1 = addressMap.get(bean1.code);
                                return list1.indexOf(thirdValue);
                            }
                        });
                    }
                };
                new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
            } else if (position == 10) {
                BottomPopup bottomPopup = new BottomPopup<ContactEditXueliBinding>(mActivity) {
                    @OnClick(R.id.close)
                    public void quit() {
                        dismiss();
                    }

                    List<String> list = Arrays.asList("大专",
                            "本科",
                            "硕士",
                            "博士");

                    @Override
                    protected void initView() {
                        super.initView();
                        mBinding.edu.setData(list);
                    }

                    @OnClick(R.id.confirm)
                    public void confirm() {
                        int currentPosition = mBinding.edu.getCurrentPosition();
                        bean.right = list.get(currentPosition);
                        contactBean.edu = currentPosition + 1;
                        topAdapter.notifyDataSetChanged();
                        dismiss();
                    }

                };
                new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
            } else if (position == 11) {
                BottomPopup bottomPopup = new BottomPopup<ContactEditMarryBinding>(mActivity) {
                    @OnClick(R.id.close)
                    public void quit() {
                        dismiss();
                    }

                    List<String> list = Arrays.asList("已婚",
                            "未婚");

                    @Override
                    protected void initView() {
                        super.initView();
                        mBinding.edu.setData(list);
                    }

                    @OnClick(R.id.confirm)
                    public void confirm() {
                        int currentPosition = mBinding.edu.getCurrentPosition();
                        bean.right = list.get(currentPosition);
                        contactBean.maritalStatus = currentPosition + 1;
                        topAdapter.notifyDataSetChanged();
                        dismiss();
                    }

                };
                new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
            }
        }
    };
    @BindAdapter(R.id.recyclerViewMid)
    BaseAdapter<ItemDetailMidBinding, ContactBean.JobList> midAdapter = new BaseAdapter<ItemDetailMidBinding, ContactBean.JobList>() {
        @Override
        protected void onBindData(ItemDetailMidBinding binding, ContactBean.JobList jobList, int position) {
            super.onBindData(binding, jobList, position);
            if (position == 0) {
                binding.header.setVisibility(GONE);
            } else {
                binding.header.setVisibility(VISIBLE);
                binding.old.setText("过往工作（" + position + "/5）");
            }
            List<Label.LabelBean> mid = new ArrayList<>();
            mid.add(new Label.LabelBean("公司名称", StringUtil.getDefault(jobList.name, ""), "点击输入公司名称", false));
            mid.add(new Label.LabelBean("当前行业", StringUtil.getDefault(jobList.industryName, "请选择行业"), true));
            mid.add(new Label.LabelBean("当前职位", StringUtil.getDefault(jobList.positionName, "请选择职位"), true));
            mid.add(new Label.LabelBean("公司地址", StringUtil.getDefault(jobList.address, ""), "点击输入公司地址", false));
            BaseAdapter<ItemDetailTopBinding, Label.LabelBean> jobAdapter = new BaseAdapter<ItemDetailTopBinding, Label.LabelBean>() {
                @Override
                protected void onBindData(ItemDetailTopBinding binding, Label.LabelBean bean, int position) {
                    super.onBindData(binding, bean, position);
                    if (position == 0) {
                        binding.tvValue.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                jobList.name = s.toString();
                            }

                            @Override
                            public void afterTextChanged(Editable s) {

                            }
                        });
                    } else if (position == 3) {
                        binding.tvValue.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                jobList.address = s.toString();
                            }

                            @Override
                            public void afterTextChanged(Editable s) {

                            }
                        });
                    }

                }

                @OnClick(R.id.iv_arrow)
                public void clickRight(int position, Label.LabelBean bean) {
                    if (position == 1) {
                        if (industryBeanList == null || industryBeanList.isEmpty()) {
                            return;
                        }
                        BottomPopup bottomPopup = new BottomPopup<ContactEditIndustryBinding>(mActivity) {
                            @OnClick(R.id.close)
                            public void quit() {
                                dismiss();
                            }

                            @Override
                            protected void initData() {
                                super.initData();
                            }

                            @Override
                            protected void initView() {
                                super.initView();
                                mBinding.edu.setFormatter(new WheelFormatter() {
                                    @Override
                                    public String formatItem(@NonNull Object item) {
                                        if (item instanceof IndustryBean) {
                                            IndustryBean industryBean = (IndustryBean) item;
                                            return industryBean.name;
                                        }
                                        return "";
                                    }
                                });
                                mBinding.edu.setData(industryBeanList);
                            }

                            @OnClick(R.id.confirm)
                            public void confirm() {
                                int currentPosition = mBinding.edu.getCurrentPosition();
                                bean.right = industryBeanList.get(currentPosition).name;
                                jobList.industryId = industryBeanList.get(currentPosition).id;
                                jobList.industryName = industryBeanList.get(currentPosition).name;
                                notifyDataSetChanged();
                                dismiss();
                            }

                        };
                        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
                    } else if (position == 2) {
                        if (positionBeanList == null || positionBeanList.isEmpty()) {
                            return;
                        }
                        BottomPopup bottomPopup = new BottomPopup<ContactEditPositionBinding>(mActivity) {
                            @OnClick(R.id.close)
                            public void quit() {
                                dismiss();
                            }

                            @Override
                            protected void initData() {
                                super.initData();
                            }

                            @Override
                            protected void initView() {
                                super.initView();
                                mBinding.edu.setFormatter(new WheelFormatter() {
                                    @Override
                                    public String formatItem(@NonNull Object item) {
                                        if (item instanceof PositionBean) {
                                            PositionBean industryBean = (PositionBean) item;
                                            return industryBean.name;
                                        }
                                        return "";
                                    }
                                });
                                mBinding.edu.setData(positionBeanList);
                            }

                            @OnClick(R.id.confirm)
                            public void confirm() {
                                int currentPosition = mBinding.edu.getCurrentPosition();
                                bean.right = positionBeanList.get(currentPosition).name;
                                jobList.positionId = positionBeanList.get(currentPosition).id;
                                jobList.positionName = positionBeanList.get(currentPosition).name;
                                notifyDataSetChanged();
                                dismiss();
                            }

                        };
                        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
                    }
                }
            };
            binding.recyclerView.setAdapter(jobAdapter);
            jobAdapter.setData(mid);
        }

        @OnClick(R.id.remove)
        public void clickRight(int position) {
            contactBean.jobList.remove(position);
            midAdapter.setData(contactBean.jobList);
        }
    };

    private void refreshBean() {
        mBinding.setBean(contactBean);
    }

    @Override
    protected void initData() {
        super.initData();
        int avatar = AvatarUtil.getAvatar(contactBean.gender);
        mBinding.avatar.setImageResource(avatar);

        if (contactList.isEmpty()) {
            mBinding.addContacts.setVisibility(GONE);
            mBinding.emptyContacts.setVisibility(VISIBLE);
        } else {
            mBinding.addContacts.setVisibility(VISIBLE);
            mBinding.emptyContacts.setVisibility(GONE);
        }
        if (commons.isEmpty()) {
            ContactCreateActivity.this.mBinding.emptyCommon.setVisibility(VISIBLE);
            ContactCreateActivity.this.mBinding.addCommon.setVisibility(GONE);
        } else {
            ContactCreateActivity.this.mBinding.addCommon.setVisibility(VISIBLE);
            ContactCreateActivity.this.mBinding.emptyCommon.setVisibility(GONE);
        }
        List<Label3.LabelBean> noticeList = new ArrayList<>();
        noticeList.add(new Label3.LabelBean("生日提醒", ""));
        noticeList.add(new Label3.LabelBean("节日提醒", ""));
        noticeList.add(new Label3.LabelBean("礼物提醒", ""));
        noticeList.add(new Label3.LabelBean("人物周期提醒", "点击选择周期提醒"));
        noticeAdapter.setData(noticeList);

        List<Label.LabelBean> list = new ArrayList<>();
        list.add(new Label.LabelBean("性别", StringUtil.getDefault(SexUtil.getName(contactBean.gender), "请选择性别"), true));
        list.add(new Label.LabelBean("手机号", StringUtil.getDefault(contactBean.mobile, ""), "请输入手机号", false));
        list.add(new Label.LabelBean("农历出生日期", StringUtil.getDefault(contactBean.lunarBirthday, "请选择农历出生日期"), true));
        list.add(new Label.LabelBean("阳历出生日期", StringUtil.getDefault(contactBean.birthday, "请选择阳历出生日期"), true));
        list.add(new Label.LabelBean("年龄", contactBean.age == 0 ? "根据日期自动生成" : String.valueOf(contactBean.age), false));
        list.add(new Label.LabelBean("星座", StringUtil.getDefault(contactBean.constellation, "根据日期自动生成"), false));
        list.add(new Label.LabelBean("固定电话", StringUtil.getDefault(contactBean.telephone, ""), "请输入固定电话", false));
        list.add(new Label.LabelBean("邮箱", StringUtil.getDefault(contactBean.email, ""), "请输入邮箱", false));
        list.add(new Label.LabelBean("目前所在区域", contactBean.currentAddress == null ? "请选择省市区" : AddressUtil.getName(contactBean.currentAddress), true));
        list.add(new Label.LabelBean("家乡", contactBean.homeAddress == null ? "请选择省市区" : AddressUtil.getName(contactBean.homeAddress), true));
        list.add(new Label.LabelBean("学历", StringUtil.getDefault(EduUtil.getName(contactBean.edu), "请选择学历"), true));
        list.add(new Label.LabelBean("婚姻状况", StringUtil.getDefault(MarryUtil.getName(contactBean.maritalStatus), "请选择婚姻状况"), true));
        topAdapter.setData(list);
        List<ContactBean.JobList> jobList = contactBean.jobList;
        if (jobList == null) {
            contactBean.jobList = new ArrayList<>();
        }
        if (contactBean.jobList.isEmpty()) {
            contactBean.jobList.add(new ContactBean.JobList());
        }
        midAdapter.setData(contactBean.jobList);
        mBinding.setBean(contactBean);
        int importance = contactBean.importance;
        RadioGroupUtil.checkIndex(mBinding.importance, importance - 1);
        API.queryGroup().watch(this, new HttpCallback<List<GroupBean>>() {
            @Override
            protected void onSuccess(List<GroupBean> groupBeans) {
                GroupUtil.setGroups(groupBeans);
            }
        });


        if (contactBean.groupIdList == null) {
            contactBean.groupIdList = new ArrayList<>();
        }
        List<GroupBean> groupBeanList = new ArrayList<>();
        for (Integer i : contactBean.groupIdList) {
            GroupBean groupBean = GroupUtil.getGroupBean(i);
            if (groupBean != null) {
                groupBeanList.add(groupBean);
            }
        }
        groupAdapter.setData(groupBeanList);

        API.queryLabel().watch(this, new HttpCallback<List<LabelBean>>() {
            @Override
            protected void onSuccess(List<LabelBean> labelBeans) {
                Log.d(TAG, "onSuccess() called with: labelBeans = [" + labelBeans + "]");
                LabelUtil.setLabels(labelBeans);
            }
        });
        if (contactBean.labelIdList == null) {
            contactBean.labelIdList = new ArrayList<>();
        }
        List<LabelBean> labelBeanList = new ArrayList<>();
        for (Integer i : contactBean.labelIdList) {
            LabelBean groupBean = LabelUtil.getBean(i);
            if (groupBean != null) {
                labelBeanList.add(groupBean);
            }
        }
        labelAdapter.setData(labelBeanList);


        API.getIndustry().
                watch(this, new HttpCallback<List<IndustryBean>>() {
                    @Override
                    protected void onSuccess(List<IndustryBean> contactBeans) {
                        industryBeanList = contactBeans;
                    }
                });
        API.getPosition().

                watch(this, new HttpCallback<List<PositionBean>>() {
                    @Override
                    protected void onSuccess(List<PositionBean> positionBeans) {
                        positionBeanList = positionBeans;
                    }
                });
        API.getAddress().

                watch(this, new HttpCallback<List<AddressBean>>() {

                    @Override
                    protected void onSuccess(List<AddressBean> contactBeans) {
                        AddressUtil.init(contactBeans);
                        for (AddressBean bean : contactBeans) {
                            if (bean.level == 1) {
                                addressLevel1.add(bean);
                            } else {
                                String parentCode = bean.parentCode;
                                addressMap.computeIfAbsent(parentCode, new Function<String, List<AddressBean>>() {
                                    @Override
                                    public List<AddressBean> apply(String s) {
                                        return new ArrayList<>();
                                    }
                                }).add(bean);
                            }
                        }

                    }
                });

        if (BuildConfig.DEBUG) {
//            goLabel(null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
        if (requestCode == 102) {
        } else if (requestCode == 103) {
            if (data == null) {
                return;
            }
            String group = data.getStringExtra("group");
            if (group == null || group.isEmpty()) {
                return;
            }
            List<ContactBean> list = GsonUtil.fromJson(group, new TypeToken<List<ContactBean>>() {
            }.getType());
            contactList.clear();
            contactList.addAll(list);
            if (contactList.isEmpty()) {
                mBinding.addContacts.setVisibility(GONE);
                mBinding.emptyContacts.setVisibility(VISIBLE);
            } else {
                mBinding.addContacts.setVisibility(VISIBLE);
                mBinding.emptyContacts.setVisibility(GONE);
            }
            contactAdapter.setData(contactList);
            Log.i(TAG, "onActivityResult: " + list);
        }
    }

    List<AddressBean> addressLevel1 = new ArrayList<>();
    Map<String, List<AddressBean>> addressMap = new HashMap<>();
    List<IndustryBean> industryBeanList;
    List<PositionBean> positionBeanList;
    ContactBean contactBean = new ContactBean();
    @BindAdapter(R.id.groupRecyclerView)
    BaseAdapter<ItemEditGroupBinding, GroupBean> groupAdapter = new BaseAdapter<ItemEditGroupBinding, GroupBean>() {
    };
    @BindAdapter(R.id.labelRecyclerView)
    BaseAdapter<ItemEditLabelBinding, LabelBean> labelAdapter = new BaseAdapter<ItemEditLabelBinding, LabelBean>() {
    };
    @BindAdapter(R.id.contactRecyclerView)
    BaseAdapter<ItemContactEditContactBinding, ContactBean> contactAdapter = new BaseAdapter<ItemContactEditContactBinding, ContactBean>() {
        @Override
        protected void onBindData(ItemContactEditContactBinding binding, ContactBean bean, int position) {
            super.onBindData(binding, bean, position);
            binding.avatar.setImageResource(AvatarUtil.getAvatar(bean.gender));
            LinearLayoutManager layoutManager = (LinearLayoutManager) binding.groupRecyclerView.getLayoutManager();
            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            BaseAdapter<ItemSelectGroupDetailBinding, GroupBean> groupBeanBaseAdapter = new BaseAdapter<ItemSelectGroupDetailBinding, GroupBean>() {
            };
            binding.groupRecyclerView.setAdapter(groupBeanBaseAdapter);
            groupBeanBaseAdapter.setData(bean.relationGroupList);
        }
    };
    @BindAdapter(R.id.noticeRecyclerView)
    BaseAdapter<CommonLabel3Binding, Label3.LabelBean> noticeAdapter = new BaseAdapter<CommonLabel3Binding, Label3.LabelBean>() {
        @Override
        protected void onBindData(CommonLabel3Binding binding, Label3.LabelBean bean, int position) {
            super.onBindData(binding, bean, position);
            if (position == 0) {
                binding.noticeSwitch.setSelected(false);
                if (contactBean.birthdayContactsTip != null) {
                    BirthdayTip birthdayTip = contactBean.birthdayContactsTip;
                    binding.noticeSwitch.setSelected(birthdayTip.tipStatus);
                }
            } else if (position == 1) {
                binding.noticeSwitch.setSelected(false);
                if (contactBean.festivalContactsTip != null) {
                    FestivalTip birthdayTip = contactBean.festivalContactsTip;
                    binding.noticeSwitch.setSelected(birthdayTip.tipStatus);
                }
            } else if (position == 2) {
                binding.noticeSwitch.setSelected(false);
                if (contactBean.giftTip != null) {
                    binding.noticeSwitch.setSelected(contactBean.giftTip.tipStatus);
                }
            }
        }

        @OnClick(R.id.noticeSwitch)
        public void noticeSwitch(int position, CommonLabel3Binding binding) {
            Log.d(TAG, "noticeSwitch() called with: position = [" + position + "], btn = [" + "]");
            saveInfo();
            if (position == 0) {
                if (TextUtils.isEmpty(contactBean.birthday) || TextUtils.isEmpty(contactBean.lunarBirthday)) {
                    ToastUtils.showShort("请先完善生日");
                    return;
                }
                DataStore.put(ContactEditActivity.CONTACT_BEAN_KEY, contactBean);
                startActivityForResult(BirthdayActivity.class, new Runnable() {
                    @Override
                    public void run() {
                        BirthdayTip birthdayTip = DataStore.get(BirthdayActivity.KEY);
                        if (birthdayTip != null) {
                            Log.d(TAG, "run() called" + GsonUtil.toJson(birthdayTip));
                            contactBean.birthdayContactsTip = birthdayTip;
                            contactBean.birthdayTipStatus = true;
                            notifyDataSetChanged();
                        }
                    }
                });
            } else if (position == 1) {
                DataStore.put(FestivalActivity.KEY, contactBean.festivalContactsTip);
                startActivityForResult(FestivalActivity.class, new Runnable() {
                    @Override
                    public void run() {
                        FestivalTip birthdayTip = DataStore.get(FestivalActivity.KEY);
                        if (birthdayTip != null) {
                            Log.d(TAG, "run() called" + GsonUtil.toJson(birthdayTip));
                            contactBean.festivalContactsTip = birthdayTip;
                            notifyDataSetChanged();
                        }
                    }
                });
            } else if (position == 2) {
                DataStore.put(GiftActivity.KEY, contactBean.giftTip);
                startActivityForResult(GiftActivity.class, new Runnable() {
                    @Override
                    public void run() {
                        GiftTip birthdayTip = DataStore.get(GiftActivity.KEY);
                        if (birthdayTip != null) {
                            Log.d(TAG, "run() called" + GsonUtil.toJson(birthdayTip));
                            contactBean.giftTip = birthdayTip;
                            contactBean.giftTipStatus = true;
                            notifyDataSetChanged();
                        }
                    }
                });
            }
        }

        @OnClick(R.id.iv_arrow)
        public void iv_arrow(int position, CommonLabel3Binding binding) {
            Log.d(TAG, "noticeSwitch() called with: position = [" + position + "], btn = [" + "]");
            saveInfo();
            if (contactBean.contactsCycleTip != null) {
                EventBus.getDefault().postSticky(contactBean.contactsCycleTip);
            }
            startActivityForResult(CycleActivity.class, new Runnable() {
                @Override
                public void run() {
                    ContactBean.CycleTip birthdayTip = DataStore.get(CycleActivity.KEY_CYCLE);
                    if (birthdayTip != null) {
                        Log.d(TAG, "run() called" + GsonUtil.toJson(birthdayTip));
                        contactBean.contactsCycleTip = birthdayTip;
                        String str = "";
                        if (birthdayTip.cycleType == 1) {
                            str = "每" + birthdayTip.cycleTime + "天";
                        } else if (birthdayTip.cycleType == 2) {
                            str = "每" + birthdayTip.cycleTime + "周";
                        } else {
                            str = "每月";
                        }
                        binding.tvValue.setText(str);
                    }

                }
            });
        }
    };
    @BindAdapter(R.id.commonRecyclerView)
    BaseAdapter<ItemEditCommonBinding, String> commonAdapter = new BaseAdapter<ItemEditCommonBinding, String>() {
        @Override
        protected void onBindData(ItemEditCommonBinding binding, String bean, int position) {
            binding.text.setText(bean);
        }
    };

    @Override
    protected void initView() {
        super.initView();
        ContactBean bean = DataStore.get(ContactEditActivity.CONTACT_BEAN_KEY);
        if (bean != null) {
            contactBean = bean;
        }
        LinearLayoutManager layoutManager = (LinearLayoutManager) mBinding.commonRecyclerView.getLayoutManager();
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        List<String> list = GsonUtil.fromJson(contactBean.common, new TypeToken<List<String>>() {
        }.getType());
        if (list != null) {
            commons.addAll(list);
        }
        commonAdapter.setData(commons);
    }

    public void save(View view) {
        saveInfo();
        List<ContactBean.JobList> jobList = contactBean.jobList;
        if (jobList != null) {
            if (jobList.size() == 1) {
                ContactBean.JobList jobList1 = jobList.get(0);
                if (jobList1.positionId == 0 && jobList1.industryId == 0 && TextUtils.isEmpty(jobList1.address) && TextUtils.isEmpty(jobList1.name)) {
                    jobList.remove(0);
                }
            }
//            for (ContactBean.JobList list : jobList) {
//                if (list.positionId == 0 || list.industryId == 0) {
//                    ToastUtils.showShort("请完善工作信息");
//                    return;
//                }
//            }
        }
        API.contactsAdd(contactBean).watch(this, new HttpCallback<Integer>() {
            @Override
            protected void onSuccess(Integer aBoolean) {
                Log.d(TAG, "onSuccess() called with: aBoolean = [" + aBoolean + "]");
                finish();
            }
        });
    }

    private void saveInfo() {
        Label.LabelBean labelBean = topAdapter.getData().get(1);
        contactBean.mobile = labelBean.right;
        contactBean.telephone = topAdapter.getData().get(6).right;
        contactBean.email = topAdapter.getData().get(7).right;

        contactBean.importance = RadioGroupUtil.getCheckedIndex(mBinding.importance) + 1;
        contactBean.contactsList = new ArrayList<>();
        for (ContactBean bean : contactList) {
            contactBean.contactsList.add(bean.id);
        }
        contactBean.contactsRelationalList = new ArrayList<>();
        for (ContactBean bean : contactList) {
            contactBean.contactsRelationalList.add(new ContactBean.ContactList(bean));
        }
        contactBean.common = GsonUtil.toJson(commons);
        Log.i(TAG, "saveInfo: " + GsonUtil.toJson(contactBean));
    }

    List<ContactBean> contactList = new ArrayList<>();

    public void goGroup(View view) {
        Log.d(TAG, "goGroup() called with: view = [" + view + "]");
        List<GroupBean> data = groupAdapter.getData();
        DataStore.put(GroupActivity.key, data);
        startActivityForResult(GroupActivity.class, new Runnable() {
            @Override
            public void run() {
                List<GroupBean> list = DataStore.get(GroupActivity.key);
                if (list == null || list.isEmpty()) {
                    return;
                }
                groupAdapter.setData(list);
                if (contactBean.groupIdList == null) {
                    contactBean.groupIdList = new ArrayList<>();
                }
                contactBean.groupIdList.clear();
                for (GroupBean bean : list) {
                    contactBean.groupIdList.add(bean.id);
                }
                Log.i(TAG, "onActivityResult: " + list);
            }
        });
    }

    public void goLabel(View view) {
        DataStore.put(LabelActivity.key, labelAdapter.getData());
        startActivityForResult(LabelActivity.class, new Runnable() {
            @Override
            public void run() {
                List<LabelBean> labelBeanList = DataStore.get(LabelActivity.key);
                if (labelBeanList != null) {
                    labelAdapter.setData(labelBeanList);
                    if (contactBean.labelIdList == null) {
                        contactBean.labelIdList = new ArrayList<>();
                    }
                    contactBean.labelIdList.clear();
                    for (LabelBean bean : labelBeanList) {
                        contactBean.labelIdList.add(bean.id);
                    }
                }
            }
        });
    }

    public void goContacts(View view) {
        DataStore.put(ContactSelectActivity.class.getName(), contactBean);
        startActivityForResult(new Intent(this, ContactSelectActivity.class), 103);
    }

    List<String> commons = new ArrayList<>();

    public void showCommon(View view) {
        BottomPopup bottomPopup = new BottomPopup<PopContactEditCommonBinding>(mActivity) {
            @OnClick(R.id.close)
            public void quit() {
                dismiss();
            }

            @Override
            protected void initData() {
                super.initData();
            }

            @Override
            protected void initView() {
                super.initView();
            }

            @OnClick(R.id.confirm)
            public void confirm() {
                commons.add(mBinding.input.getText().toString().trim());
                commonAdapter.setData(commons);
                if (commons.isEmpty()) {
                    ContactCreateActivity.this.mBinding.emptyCommon.setVisibility(VISIBLE);
                    ContactCreateActivity.this.mBinding.addCommon.setVisibility(GONE);
                } else {
                    ContactCreateActivity.this.mBinding.addCommon.setVisibility(VISIBLE);
                    ContactCreateActivity.this.mBinding.emptyCommon.setVisibility(GONE);
                }
                dismiss();
            }

        };
        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
    }

    public void changeAvatar(View view) {
        PictureUtil.choosePic(mActivity, 1, new PictureUtil.Callback() {
            @Override
            public void onSuccess(String s) {
                contactBean.avatar = s;
                ImageUtil.loadCircle(mBinding.avatar, s);
            }
        });
    }

    public void importanceLow(View view) {
        RadioGroupUtil.checkIndex(mBinding.importance, 0);
    }

    public void importanceMid(View view) {
        RadioGroupUtil.checkIndex(mBinding.importance, 1);
    }

    public void importanceHigh(View view) {
        RadioGroupUtil.checkIndex(mBinding.importance, 2);
    }

    public void addJob(View view) {
        Log.d(TAG, "addJob() called with: view = [" + view + "]");
        if (contactBean.jobList.size() < 6) {
            contactBean.jobList.add(new ContactBean.JobList());
            midAdapter.setData(contactBean.jobList);
        }
    }

}